package com.yc;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 多线程服务器聊天
 *
 * @author zwei
 * @create 2024-07-19 9:52
 */
public class Test4_talkServer_runnable {
    private static Logger logger = Logger.getLogger(Test4_talkServer.class.getName());

    public static void main(String[] args) throws IOException {
        final int port = 10000;
        ServerSocket ss = null;
        for (int i = port; i < 65535; i++) {
            try {
                //完成一台时间服务  选择合适端口的工作
                ss = new ServerSocket(i);
                break;
            } catch (Exception e) {
                e.printStackTrace();
                if (e instanceof BindException) {
                    logger.info("端口" + i + "被占用");
                }
            }
        }
        System.out.println(ss.getInetAddress().getHostAddress() + "启动了，监听了端口号" + ss.getLocalPort());
        //客户端通过键盘录入聊天信息
        while (true) {
            Socket socket = ss.accept();
            System.out.println("客户端" + socket.getRemoteSocketAddress() + "连接上来了");
            TalkTask task=new TalkTask(socket);
            Thread thread=new Thread(task);
            thread.start();
        }
    }
}

class TalkTask implements Runnable {
    private Socket socket;
    Scanner scanner = new Scanner(System.in);   //键盘的标准输入流

    public TalkTask(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        //套接字流
        try (
                Socket socket = this.socket;    //为什么要在这重新赋值一次？因为语法规定try要自动关闭的流必须在try()声明
                //套接字流
                Scanner clientReader = new Scanner(socket.getInputStream());   //Scanner.nextLine() 按n来读取
                PrintWriter pw = new PrintWriter(socket.getOutputStream());    //PrintWriter.writeLine() --输出数据\n
        ) {
            do {
                String response = clientReader.nextLine();
                System.out.println("客户端" + socket.getRemoteSocketAddress() + "对server说：" + response);
                if ("bye".equalsIgnoreCase(response)) {
                    System.out.println("客户端" + socket.getRemoteSocketAddress() + "主动断开与服务器的连接");
                    break;
                }
                System.out.println("请输入服务器想对客户端" + socket.getRemoteSocketAddress() + "说的话：");
                String line = scanner.nextLine();
                pw.println(line);
                pw.flush();
                if ("bye".equalsIgnoreCase(line)) {
                    System.out.println("服务器要求主动断开与客户端" + socket.getRemoteSocketAddress() + "的连接");
                    break;
                }
            } while (true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("在服务端正常结束与客户端" + socket.getRemoteSocketAddress() + "聊天。。。");
    }
}
